const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, extractNumber, getNextId, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');
const fs = require('fs');
const path = require('path');

// 获取回访记录
router.get('/', authenticateToken, async (req, res) => {
    try {
        const { cust_id, task_id, emp_id, actual_date } = req.query;
        let sql = 'SELECT * FROM revisit_record WHERE 1=1';
        if (task_id) {
            sql += ` AND task_id = '${task_id}'`;
        }
        if (emp_id) {
            sql += ` AND emp_id = '${emp_id}'`;
        }
        if (actual_date) {
            sql += ` AND actual_date = '${actual_date}'`;
        }
        if (cust_id) {
            sql += ` AND cust_id = '${cust_id}'`;
        }
        const [result] = await db.execute(sql);

        // 获取客户信息
        const [cust_info] = await db.execute(`SELECT cust_id, cust_name FROM customer`);
        // 获取员工信息
        const [emp_info] = await db.execute(`SELECT emp_id, emp_name FROM employee`);

        result.forEach(item => {
            item.actual_date = dayjs(item.actual_date).format('YYYY-MM-DD');
            item.cust_name = cust_info.find(cust => cust.cust_id === item.cust_id)?.cust_name || '';
            item.emp_name = emp_info.find(emp => emp.emp_id === item.emp_id)?.emp_name || '';
        });
        await logUserOperation(req, '查询', '获取回访记录', '获取回访记录成功', '成功');
        res.json({
            success: true,
            message: '获取回访记录成功',
            data: result
        });
    } catch (error) {
        console.error('获取回访记录失败:', error);
        await logUserOperation(req, '查询', '获取回访记录', '获取回访记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取回访记录失败',
            error: error.message
        });
    }
});

// 新增回访记录
router.put('/add', authenticateToken, async (req, res) => {
    try {
        const { cust_id, task_id, emp_id, actual_date, result } = req.body;
        const record_id = await getNextId('RE', 'record_id', 'revisit_record', 5);
        const sql = `INSERT INTO revisit_record (record_id, cust_id, task_id, emp_id, actual_date, result) VALUES (?, ?, ?, ?, ?, ?)`;
        const params = [record_id, cust_id, task_id, emp_id, actual_date, result];
        await db.execute(sql, params);
        // await logUserOperation(req, '添加', '新增回访记录', '新增回访记录成功', '成功');
        

        // 将回访任务的回访状态修改成已回访
        await db.execute(
            `UPDATE revisit_task SET status = '已回访' WHERE task_id = ?`,
            [task_id]
        );
        res.json({
            success: true,
            message: '新增回访记录成功',
        });
    } catch (error) {
        console.error('新增回访记录失败:', error);
        // await logUserOperation(req, '添加', '新增回访记录', '新增回访记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '新增回访记录失败',
            error: error.message
        });
    }
});

// 更新回访记录
router.post('/update', authenticateToken, async (req, res) => {
    try {
        const { record_id, cust_id, task_id, emp_id, actual_date, result } = req.body;
        const sql = `UPDATE revisit_record SET cust_id = ?, task_id = ?, emp_id = ?, actual_date = ?, result = ? WHERE record_id = ?`;
        const params = [cust_id, task_id, emp_id, actual_date, result, record_id];
        await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新回访记录', '更新回访记录成功', '成功');
        res.json({
            success: true,
            message: '更新回访记录成功',
        });
    } catch (error) {
        console.error('更新回访记录失败:', error);
        await logUserOperation(req, '更新', '更新回访记录', '更新回访记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新回访记录失败',
            error: error.message
        });
    }
});

// 删除回访记录
router.delete('/delete', authenticateToken, async (req, res) => {
    try {
        const { record_id } = req.query;
        const sql = `DELETE FROM revisit_record WHERE record_id = ?`;
        const params = [record_id];
        await db.execute(sql, params);
        await logUserOperation(req, '删除', '删除回访记录', '删除回访记录成功', '成功');
        res.json({
            success: true,
            message: '删除回访记录成功',
        });
    } catch (error) {
        console.error('删除回访记录失败:', error);
        await logUserOperation(req, '删除', '删除回访记录', '删除回访记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除回访记录失败',
            error: error.message
        });
    }
});

// 获取查询项客户信息
router.get('/customer_query', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT DISTINCT revisit_record.cust_id as 'key', customer.cust_name as 'name' FROM revisit_record JOIN customer ON revisit_record.cust_id = customer.cust_id`;
        const [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取查询项客户信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取查询项客户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取查询项客户信息失败',
            error: error.message
        });
    }
});

// 获取回访任务信息
router.get('/task_query', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT DISTINCT revisit_record.task_id as 'key', revisit_record.task_id as 'name' FROM revisit_record JOIN revisit_task ON revisit_record.task_id = revisit_task.task_id`;
        const [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取回访任务信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取回访任务信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取回访任务信息失败',
            error: error.message
        });
    }
});

// 获取查询项员工信息
router.get('/employee_query', authenticateToken, async (req, res) => {
    try {
        const sql = `SELECT DISTINCT revisit_record.emp_id as 'key', employee.emp_name as 'name' FROM revisit_record JOIN employee ON revisit_record.emp_id = employee.emp_id`;
        const [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取查询项员工信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取查询项员工信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取查询项员工信息失败',
            error: error.message
        });
    }
});

module.exports = router;